package com.ourhours.message.service.wrapper;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ourhours.message.common.RedisKey;
import com.ourhours.message.domain.Supplier;
import com.ourhours.message.enums.MessageTypeEnum;
import com.ourhours.message.enums.SmsTypeEnum;
import com.ourhours.message.enums.SupplierTypeEnum;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class SupplierWrapper {

    @Autowired
    SupplierService supplierService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Value("${app_key}")
    private String smsAppKey;
    @Value("${outer_secret}")
    private String smsOuterSecret;


    private static final Logger LOGGER = LoggerFactory.getLogger(SupplierWrapper.class);

    public Supplier findSupplierWithCache(Long vendorId,Integer type){

        String key = RedisKey.MESSAGE_SUPPLIER_INFO.getKey()+vendorId+"_"+type;
        ValueOperations<String,String> operation = stringRedisTemplate.opsForValue();
        String str = operation.get(key);
        if(StringUtils.isNotBlank(str)){
            Supplier supplier = JSON.parseObject(str,Supplier.class);
            LOGGER.info("==>从redis中获取短信服务商信息成功,参数:{},{},结果:{}",vendorId,type,str);
            return supplier;
        }

        Supplier supplier = new Supplier();
        supplier.setVendorId(vendorId);
        supplier.setDeleted(0L);
        supplier.setStatus(1);
        supplier.setType(type);
        EntityWrapper<Supplier> supplierEntityWrapper = new EntityWrapper<Supplier>(supplier);
        Supplier entity = supplierService.selectOne(supplierEntityWrapper);
        if(entity==null) {
            this.initSupplier(vendorId);
        }
        Supplier entitySupplier = supplierService.selectOne(supplierEntityWrapper);
        ValueOperations<String,String> operation2 = stringRedisTemplate.opsForValue();
        operation2.set(key, JSON.toJSONString(entitySupplier),RedisKey.MESSAGE_SUPPLIER_INFO.getTerm(), TimeUnit.SECONDS);
        LOGGER.info("==>从数据库中获取短信服务商信息成功,参数:{},{},结果:{}",vendorId,type,entitySupplier);
        return entitySupplier;

    }

    public void initSupplier(Long vendorId){

        Supplier supplier = new Supplier();
        supplier.setVendorId(vendorId);
        supplier.setDeleted(0L);
        EntityWrapper<Supplier> supplierEntityWrapper = new EntityWrapper<Supplier>(supplier);
        List<Supplier> supplierList = supplierService.selectList(supplierEntityWrapper);
        Map<String,String> map = new HashMap<String,String>();
        for(Supplier supplierModel:supplierList){
            map.put(supplierModel.getType()+"",supplierModel.getSupplierType()+"");
        }
        List<Supplier> list = new ArrayList<Supplier>();
        //添加短信
        Supplier entity = new Supplier();
        //添加邮箱
        Supplier entityEmail = new Supplier();
        //添加极光
        Supplier entityPush = new Supplier();

        if(map.get("1")==null){
            entity.setVendorId(vendorId);
            entity.setOuterAppKey(smsAppKey);
            entity.setOuterSecret(smsOuterSecret);
            entity.setType(1);
            entity.setSupplierType(11);
            entity.setName("华信便利");
            entity.setOuterExtraProperty("{\"url\":\"https://dx.ipyy.net/sms.aspx\"}");
            entity.setTimesLimitPerDay(100);
            entity.setStatus(1);
            entity.setSysVersion(1);
            entity.setCreateUser("system");
            entity.setCreateTime(new Date());
            entity.setUpdateUser("system");
            entity.setUpdateTime(new Date());
            entity.setDeleted(0L);
            list.add(entity);
        }

        if(map.get("2")==null){
            //添加邮箱
            entityEmail.setVendorId(vendorId);
            entityEmail.setOuterAppKey("auto-sender@ourhours.net");
            entityEmail.setOuterSecret("Thce365");
            entityEmail.setType(2);
            entityEmail.setSupplierType(21);
            entityEmail.setName("org.apache.commons.mail");
            entityEmail.setOuterExtraProperty("{\"sourceName\":\"全时后台系统\",\"sourceServer\":\"smtp.exmail.qq.com\"}");
            entityEmail.setTimesLimitPerDay(100);
            entityEmail.setStatus(1);
            entityEmail.setSysVersion(1);
            entityEmail.setCreateUser("system");
            entityEmail.setCreateTime(new Date());
            entityEmail.setUpdateUser("system");
            entityEmail.setUpdateTime(new Date());
            entityEmail.setDeleted(0L);
            list.add(entityEmail);
        }
        if(map.get("3")==null){
            //添加推送
            entityPush.setVendorId(vendorId);
            entityPush.setOuterAppKey("112e01209c38cc4121a4a9e4");
            entityPush.setOuterSecret("08aca2d8d48582295e451138");
            entityPush.setType(3);
            entityPush.setSupplierType(31);
            entityPush.setName("极光推送");
            entityPush.setOuterExtraProperty("{}");
            entityPush.setTimesLimitPerDay(100);
            entityPush.setStatus(1);
            entityPush.setSysVersion(1);
            entityPush.setCreateUser("system");
            entityPush.setCreateTime(new Date());
            entityPush.setUpdateUser("system");
            entityPush.setUpdateTime(new Date());
            entityPush.setDeleted(0L);
            list.add(entityPush);
        }

        if(list.size()>0){
            supplierService.insertBatch(list);
            LOGGER.info("==>supplierWrapper.initSupplier添加供应商信息成功,参数:{}",vendorId);
        }
        LOGGER.info("==>supplierWrapper.initSupplier未添加供应商信息，数据库已存在,参数:{}",vendorId);

    }

    public void addSupplierCache(Supplier entity)  {
        String key = RedisKey.MESSAGE_SUPPLIER_INFO.getKey()+entity.getVendorId()+"_"+entity.getType();
        ValueOperations<String,String> operation = stringRedisTemplate.opsForValue();
        operation.set(key, JSON.toJSONString(entity),RedisKey.MESSAGE_SUPPLIER_INFO.getTerm(), TimeUnit.SECONDS);
    }

    public void delSupplierCache(Supplier entity){
        String key = RedisKey.MESSAGE_SUPPLIER_INFO.getKey()+entity.getVendorId()+"_"+entity.getType();
        stringRedisTemplate.delete(key);
    }
}

